package jgcp.worker;

import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;

import jgcp.common.Task;
import jgcp.common.network.Connection;
import jgcp.common.network.FileReceiver;
import jgcp.config.Configuration;
import jgcp.message.Message;
import jgcp.message.MessageHandler;
import jgcp.message.MessageType;
import jgcp.worker.process.TaskQueue;
import jgcp.worker.service.WorkerService;
/**
 * 
 * @Date 31/05/2009
 * @author Jie Zhao (288654)
 * @version 1.0
 */
public class WorkerMessageHandler extends MessageHandler {
	private static AtomicInteger AI = new AtomicInteger(1);

	public WorkerMessageHandler(Connection c) {
		super(c);
	}

	public void processMessage(Message m) throws Exception {
		if (m.getType() == MessageType.SENDTASK) {
			int port = Integer.parseInt(m.getMessageBody());
			String tempName = Configuration.getInstance().getWorkerTempfolder()
					+ "temp" + AI.getAndIncrement() + ".zip";
			FileReceiver<Task> receiver = new FileReceiver<Task>(connection
					.getAddress(), port, tempName);
			receiver.start();
			while (receiver.isAlive())
				; // waiting for receive.
			Task t = receiver.getObject();
			File file = new File(tempName);
			String destName = Configuration.getInstance().getWorkerTempfolder()
					+ "task" + t.getTaskid() + ".zip";
			File dest = new File(destName);
			if (file.exists()) {
				if (file.renameTo(dest)) {
					t.setFile(destName);
				} else {
					t.setFile(tempName);
				}
			}
			TaskQueue.getInstance().put(t);
		}
		else if(m.getType()== MessageType.CANCELTASK)
		{
			int taskid = Integer.parseInt(m.getMessageBody());
			WorkerService.getInstance().cancelTask(taskid);
			Message msg = new Message();
			msg.setType(MessageType.CANCELTASK_ACK);
			msg.setMessageBody(""+taskid);
			connection.writeData(msg.toByteArray());
		}
		
		else {
			super.processMessage(m);
		}
	}

}
